#!/usr/bin/perl
#
# Trace out recent referers to the Linux Counter
#
$minref = 2;
while ($ARGV[0] =~ /^-/) {
    $opt = shift;
    if ($opt eq "-t") {
	$printtourl = 1;
    } elsif ($opt eq "--") {
	last;
    }
}
$file = shift;
if (!$file) {
    open(IN, "tail -10000f /var/log/httpd/referer_log|") || die "Could not tail\n";
} else {
    open(IN, $file) || die "Could not open $file\n";
}
$| = 1;
while (<IN>) {
    chop;
    next if ! / counter.li.org /;
    next if m!Referer:http://counter.li.org!;
    next if m!Referer:-!;
    $type = "unparsed";
    if (/"\S{3,5} (\S+) HTTP\/.*"/) {
	$tourl = $1;
	if ($tourl =~ /certificate.cgi/) {
	    $type = "cert";
	} elsif ($tourl eq "/") {
	    $type = "root";
	} elsif ($tourl =~ /.gif/) {
	    $type = "gif";
	} else {
	    $type = "other";
	}
    }

    s/.*Referer://;
    ++ $count{$_};
    if ($printtourl) {
	print "Reference $count{$_}:$_ to $tourl\n" if $count{$_} >= $minref;
	++ $refsto{$tourl};
    } else {
	print "Reference $count{$_}:$_ ($type)\n" if $count{$_} >= $minref;
    }
}
# If we get here, summarize
for $key (sort {$refsto{$a} <=> $refsto{$b}} keys(%refsto)) {
    print "$refsto{$key} $key\n";
}
